package cn.edu.hpu.jie.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5
 * @author Jie
 *
 */
public class HashUtil {
	
	/**
	 * 计算32位的字符串MD5值
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static String getHashString(byte[] str) throws Exception {
		byte[] hashArray = getHashBytes(str);
		
		StringBuffer sb = new StringBuffer();
		
		for(int i = 0; i < hashArray.length; i++) {
			int h = hashArray[i] & 0xFF;
			if(h < 16) {
				sb.append("0");
			}
			
			sb.append(Integer.toString(h, 16));
		}
		
		return sb.toString();
	}
	
	/**
	 * 生成MD5 byte[]数组
	 * @param data
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static byte[] getHashBytes(byte[] data) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.reset();
		md.update(data);
		return md.digest();
	}
}
